"""
MEMESA-TOOLS
============
Model preparation, vertex enumeration and vertex analysis tools developed as
part of the MEMESA project.

    Copyright (C) 2009-2012 Brett G. Olivier and Steven M. Kelk

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>

Author: Brett G. Olivier
Contact email: bgoli@users.sourceforge.net

"""

# Set userdata here #

work_dir = 'iAF1260'
# model_name = 'Ecoli_iAF1260.base'
# input_objective = ['R_EX_glc_e_','R_EX_lcts_e_','R_EX_glu_L_e_','R_EX_gln_L_e_'] # 1.0
# input_objective = ['R_EX_ac_e_','R_EX_succ_e_'] # 0.1
#model_name = 'Ecoli_iAF1260_ox.base'
#input_objective = ['R_EX_glc_e_','R_EX_lcts_e_','R_EX_ac_e_','R_EX_succ_e_'] # 1.0
##  model_name = 'Ecoli_iAF1260_ox_nh4.base'
model_name = 'Ecoli_iAF1260_noox.base'
input_objective = ['R_EX_glc_e_'] # 1.0

# General settings
myInf = 999999
target_biomass = 1.0
USE_ALL_EXCHANGE = False

# End set userdata#


### Active script ###

import os, time, numpy
cDir = os.path.dirname(os.path.abspath(os.sys.argv[0]))
model_file = model_name + '.xml'
model_dir = os.path.join(cDir, work_dir, 'sbml')
work_dir = os.path.join(cDir, work_dir, 'init_model')


from pyscescbm.CBVersion import __DEBUG__, __version__
from pyscescbm import CBRead, CBWrite, CBTools
from pyscescbm import CBSolver as slv

print '\n**********\nWelcome to the PySCeS Constraint Based Modelling Toolkit (%s)\n**********\n' % __version__

work_dir = os.path.join(cDir, work_dir)
if not os.path.exists(work_dir):
    os.mkdir(work_dir)

mod = CBRead.readSBML2FBA(model_file, work_dir=model_dir)
model_name = '%s.uptake' % (model_name)
mod.id = model_name

CBTools.processBiGGchemFormula(mod)
CBTools.processSBMLAnnotationNotes(mod, annotation_key='note')

if USE_ALL_EXCHANGE:
    input_objective, medDict = CBTools.processExchangeReactions(mod, key=None)

# get active (1st) objfunc
biomass_name = mod.objectives[mod.activeObjIdx].fluxObjectives[0].reaction
# write LP
CBTools.addStoichToFBAModel(mod)

outData = []
for InFlux in input_objective:
    # cpx1 = slv.cplx_getModelFromObj(mod)
    cpx1 = slv.cplx_constructLPfromFBA(mod)
    slv.cplx_setObjective(cpx1, 'obj1', [(1.0, InFlux)], 'max', reset=True)
    slv.cplx_setBounds(cpx1, InFlux, min=-myInf, max=0.0)
    slv.cplx_setSingleConstraint(cpx1, 'C_'+biomass_name, expr=[(1, biomass_name)], sense='E', rhs=target_biomass)
    ##  slv.cplx_writeLPtoLPTfile(cpx1, os.path.join(work_dir, '%s(%s)_Imin' % (model_name, InFlux)), title='%s input minimization' % InFlux, Dir=None)
    slv.cplx_Solve(cpx1)
    fba_sol1, objf_name1, objf_val1 = slv.cplx_getOptimalSolution(cpx1)
    print '\nCPLEX returns objective %s = %s' % (objf_name1, objf_val1)
    slv_stat = slv.cplx_getSolutionStatus(cpx1)
    print '\nStatus: %s' % slv_stat
    outData.append((InFlux, objf_val1, target_biomass, slv_stat, mod.getReaction(InFlux).name))
    del cpx1


print '\nInput values for target: %s = %s' % (biomass_name, target_biomass)
F = file(os.path.join(work_dir, '%s.uptake.csv' % (model_file)), 'w')
F.write('input,value,OF target,status,description\n')
for D in outData:
    try:
        print '%s, %.20f, %s, %s, %s\n' % (D[0], D[1], D[2], D[3], D[4])
        F.write('%s,%.20f,%s,%s,%s\n' % (D[0], D[1], D[2], D[3], D[4]))
    except TypeError:
        F.write('%s,%s,%s,%s,%s\n' % (D[0], D[1], D[2], D[3], D[4]))

F.flush()
F.close()



